#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>
#include <QThread>
#include <QCloseEvent>
#include "./tools/logic/datahandler.h"
#include "./tools/database/servicemanager.h"

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_clientConnector = new ClientConnector;

    InitThreads();
    tcpThread->start();

    // DBConnectionPool* pool = DBConnectionPool::GetInstance();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitThreads()
{
    // 网络收发线程
    tcpThread = new QThread();
    m_clientConnector->moveToThread(tcpThread);
    // 线程启动就部署服务器
    connect(tcpThread, &QThread::started, m_clientConnector, &ClientConnector::InitTcpServer);
    // 确保线程退出时销毁对象
    connect(tcpThread, &QThread::finished, m_clientConnector, &QObject::deleteLater);
    connect(tcpThread, &QThread::finished, tcpThread, &QObject::deleteLater);


    // 业务逻辑处理线程
    handlerThread = new QThread();
    DataHandler::getInstance().moveToThread(handlerThread);
    // 确保线程退出时销毁对象
    connect(handlerThread, &QThread::finished, &DataHandler::getInstance(), &QObject::deleteLater);
    connect(handlerThread, &QThread::finished, handlerThread, &QObject::deleteLater);
    handlerThread->start();

    // 数据库验证服务线程
    dbServiceThread = new QThread();
    ServiceManager::getInstance().moveToThread(dbServiceThread);
    // 确保线程退出时销毁对象
    connect(dbServiceThread, &QThread::finished, &ServiceManager::getInstance(), &QObject::deleteLater);
    connect(dbServiceThread, &QThread::finished, dbServiceThread, &QObject::deleteLater);
    dbServiceThread->start();

    // connect(serverConnector, &ServerConnector::ConnectionStatusChanged, this, &LoginWidget::ConnectionStatusTip);

    /* Handler和Service间的信号和槽 */
    // Handler发信号 Service的处理
    connect(&DataHandler::getInstance(), &DataHandler::dealLoginRequestMessage, &ServiceManager::getInstance(), &ServiceManager::loginCheck);
    connect(&DataHandler::getInstance(), &DataHandler::dealRegisterRequestMessage, &ServiceManager::getInstance(), &ServiceManager::registerNewUser);
    connect(&DataHandler::getInstance(), &DataHandler::dealLogoutRequestMessage, &ServiceManager::getInstance(), &ServiceManager::logout);
    connect(&DataHandler::getInstance(), &DataHandler::dealSearchUserRequestMessage, &ServiceManager::getInstance(), &ServiceManager::searchNewUser);
    connect(&DataHandler::getInstance(), &DataHandler::dealApplyFriendRequestMessageToServer, &ServiceManager::getInstance(), &ServiceManager::addFriendshipVerifyInfo);
    connect(&DataHandler::getInstance(), &DataHandler::dealApplyFriendResponseMessage, &ServiceManager::getInstance(), &ServiceManager::changeFriendshipStatus);
    connect(&DataHandler::getInstance(), &DataHandler::dealRequestBufferDataMessage, &ServiceManager::getInstance(), &ServiceManager::checkDataBuffer);
    connect(&DataHandler::getInstance(), &DataHandler::dealFriendApplicationSendStatus, &ServiceManager::getInstance(), &ServiceManager::changeFriendApplicationStatus);
    connect(&DataHandler::getInstance(), &DataHandler::dealFriendApplicationResultSendStatus, &ServiceManager::getInstance(), &ServiceManager::changeFriendApplicationResultSendStatus);
    connect(&DataHandler::getInstance(), &DataHandler::dealChatMessage, &ServiceManager::getInstance(), &ServiceManager::saveChatMessage);
    connect(&DataHandler::getInstance(), &DataHandler::dealChatMsgStatus, &ServiceManager::getInstance(), &ServiceManager::changeChatMsgStatus);
    connect(&DataHandler::getInstance(), &DataHandler::dealVideoRequest, &ServiceManager::getInstance(), &ServiceManager::transpondVideoRequest);
    connect(&DataHandler::getInstance(), &DataHandler::dealVideoResponse, &ServiceManager::getInstance(), &ServiceManager::transpondVideoResponse);





    // Service处理完返回信号，Handler处理
    connect(&ServiceManager::getInstance(), &ServiceManager::returnLoginCheckResponse,
            &DataHandler::getInstance(), &DataHandler::sendLoginResponse);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnRegisterCheckResponse,
            &DataHandler::getInstance(), &DataHandler::sendRegisterResponse);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnLogoutCheckResponse,
            &DataHandler::getInstance(), &DataHandler::sendLogoutResponse);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnSearchUserResponse,
            &DataHandler::getInstance(), &DataHandler::sendSearchUserResponse);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnOthersApplicationMessage,
            &DataHandler::getInstance(), &DataHandler::sendFriendApplicationRequest);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnFinishedApplicationResultMessage,
            &DataHandler::getInstance(), &DataHandler::sendFriendApplicationResultResponse);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnOtherChatMsg,
            &DataHandler::getInstance(), &DataHandler::sendNewChatMsg);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnVideoResponseToRequestUser,
            &DataHandler::getInstance(), &DataHandler::sendVideoResponseToRequestUser);
    connect(&ServiceManager::getInstance(), &ServiceManager::returnVideoRequestToResponseUser,
            &DataHandler::getInstance(), &DataHandler::sendVideoRequestToResponseUser);



    // 服务器断开前下线所有用户（改变数据库中所有用户在线状态）
    connect(this, &MainWindow::logoutAllUsers, &ServiceManager::getInstance(), &ServiceManager::logoutAllUsersNow);
}


// 开启服务器按钮
void MainWindow::on_StartServerBtn_clicked()
{
    // QMessageBox::critical(this, "失败", "服务器启动失败");
    // tcpThread->start();


}


void MainWindow::on_TestConnectionBtn_clicked()
{
    qDebug() << "开始测试连接";
    QTcpSocket* clientSocket = new QTcpSocket(this);
    clientSocket->connectToHost("127.0.0.1", PORT);
    connect(clientSocket, &QTcpSocket::connected, this, [](){
        qDebug() << "客户端连接成功";
    });

}



// protected:

void MainWindow::closeEvent(QCloseEvent *event)
{
    // 在关闭事件中发信号给Service线程下线用户
    qDebug() << "MainWindow closing...";
    emit logoutAllUsers();
    event->accept();
}

